package com.cms.service;

import com.cms.dao.SysRoleDao;
import com.cms.dao.SysUserDao;
import com.cms.dao.SysUserRoleDao;
import com.cms.model.bo.BussinessMsg;
import com.cms.model.dto.PwdDto;
import com.cms.model.vo.SysRole;
import com.cms.model.vo.SysUser;
import com.cms.model.vo.SysUserRole;
import com.cms.utils.annotation.SystemServiceLog;
import com.cms.utils.constant.BusinessConstants;
import com.cms.utils.constant.BussinessCode;
import com.cms.utils.constant.Constants;
import com.cms.utils.tools.BussinessMsgUtil;
import com.cms.utils.tools.MD5Utils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**系统用户服务类*/
@Service
public class SysUserService extends BaseService<SysUser>{
	
	@Autowired
    private SysUserDao userDao;
	
	@Autowired
    private SysRoleDao roleDao;
	
	@Autowired
    private SysUserRoleDao userRoleDao;

    @Autowired
    private ShiroService shiroService;

    /**
     * 根据用户Id查询用户信息
     * @param userLoginName 登陆用户名
     * @return
     */
    public SysUser selectUserByloginName(String  userLoginName){
        return userDao.selectUserByloginNameAndStatus(userLoginName,Long.valueOf(BusinessConstants.SYS_STATUS_0.getCode()));
    }
    
    /**
     * 用户信息分页显示
     * @param user 用户实体
     * @return
     */
    public String selectUserResultPageList(SysUser user){
    	PageHelper.startPage(user.getPage(),user.getLimit());
    	return setPage(this.getSysUserList(user));
    }

    /**
     * 批量用户状态失效
     * @param userIds	用户Id
     * @param loginName 当前登录用户名
     * @return
     * @throws Exception
     */
    @Transactional
    public BussinessMsg updateUserBatchStatus(String[] userIds,String loginName) throws Exception{
    	logger.info("批量失效用户开始，当前用户Id:"+Arrays.toString(userIds));
        long start = System.currentTimeMillis();
        try {
            if(null != userIds && userIds.length > 0){
                //解除用户与角色绑定关系
            	String nuserIds = StringUtils.join(userIds,",");
                userRoleDao.deleteUserRoleByUserId(nuserIds);
                //更改用户状态为1-失效
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("userStatus", BusinessConstants.SYS_STATUS_1.getCode());
                params.put("modifier", loginName);
                params.put("updateTime", new Date());
                params.put("userIds", userIds);
                userDao.updateUserByStatus(params);
                //清空用户权限缓存信息
                shiroService.clearAllCacheAuth();
            }
        } catch (Exception e) {
        	logger.error("失效用户方法内部错误",e);
            throw e;
        }finally {
        	logger.info("批量失效用户结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }

    /**
     * 保存用户信息
     * @param user 用户对象
     * @param loginName 当前登录用户
     * @return
     * @throws Exception
     */
    @Transactional
    @SystemServiceLog(description="保存用户信息Service")
    public BussinessMsg saveOrUpdateUser(SysUser user, String loginName) throws Exception{
    	logger.info("保存用户信息开始");
        long start = System.currentTimeMillis();
        try {
            //验证用户账号唯一性
            Long checkUserLoginName = userDao.selectUserLoginNameCheck(user.getUserLoginName(),user.getUserId());
            if(checkUserLoginName.intValue() > 0){
                return BussinessMsgUtil.returnCodeMessage(BussinessCode.USER_LOGIN_NAME_EXIST);
            }
            //保存用户信息
            if (null==user.getUserId()) {
                user.setUserPassword(MD5Utils.encrytor(Constants.INIT_LOGIN_PWD));
                user.setCreator(loginName);
                user.setCreateTime(new Date());
                userDao.insertSelective(user);
            } else {
                //更新用户信息
                user.setModifier(loginName);
                user.setUpdateTime(new Date());
                userDao.updateByPrimaryKeySelective(user);
            }
        } catch (Exception e) {
        	logger.error("保存用户信息方法内部错误",e);
            throw e;
        }finally {
        	logger.info("保存用户信息结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }

    /**
     * 保存用户分配角色信息
     * @param userId 用户id
     * @param roleIds 分配的角色信息
     * @param longinName 当前登录用户名称
     * @return
     * @throws Exception
     */
    @Transactional
    public BussinessMsg saveUserRole(Integer userId,String roleIds,String longinName) throws Exception{
    	logger.info("保存用户分配角色信息开始");
        long start = System.currentTimeMillis();
        try {
            List<SysUserRole> userRoles = userRoleDao.selectUserRolesListByUserId(userId);
            //如果角色Id不为空插入用户角色信息，否则删除用户下所有分配的角色
            if (StringUtils.isNotEmpty(roleIds)) {
                if (null != userRoles && !userRoles.isEmpty()) {
                    for (SysUserRole userRole : userRoles) {
                    	userRoleDao.deleteByPrimaryKey(userRole.getUserRoleId());
                    }
                }
                for (String roleId : roleIds.split(",")) {
                	SysUserRole ur = new SysUserRole();
                    ur.setUserId(userId);
                    ur.setRoleId(Integer.valueOf(roleId));
                    ur.setCreateTime(new Date());
                    ur.setCreator(longinName);
                    userRoleDao.insertSelective(ur);
                }
            } else {
                if (null != userRoles && !userRoles.isEmpty()) {
                    for (SysUserRole userRole : userRoles) {
                    	userRoleDao.deleteByPrimaryKey(userRole.getUserRoleId());
                    }
                }
            }
            // 清空用户权限缓存信息
            shiroService.clearAllCacheAuth();
        } catch (Exception e) {
        	logger.error("用户分配角色信息方法内部错误",e);
            throw e;
        }finally {
        	logger.info("保存用户分配角色信息结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
    }
    
    /**
     * 用户列表信息List
     * @param user 用户实体
     * @return
     */
    public List<SysUser> getSysUserList(SysUser user){
        List<SysUser> userList = userDao.selectSysUserList(user);
        if (null != userList && !userList.isEmpty()){
            for (SysUser u : userList) {
                SysUser userRole = selectUserRolesByUserId(u.getUserId());
                u.setRoleNames(userRole.getRoleNames());
            }
        }
        return userList;
    }
    
    /**
     * 根据用户Id查询用户角色信息
     * @param userId 用户id
     * @return
     */
    public SysUser selectUserRolesByUserId(Integer userId){
        if(userId != null){
            SysUser user = this.selectByPrimaryKey(userId);
            StringBuilder roleIds = new StringBuilder();
            StringBuilder roleNames = new StringBuilder();
            //用户所对应的角色信息
            List<SysRole> roles = roleDao.selectUserRolesByUserId(userId);
            if(null != roles && !roles.isEmpty()){
                for (SysRole role : roles) {
                	roleIds.append(role.getRoleId()).append(",");
                	roleNames.append(role.getRoleName()).append(",");
                }
                if(roleIds.length()>0){
                	roleIds.deleteCharAt(roleIds.length()-1);
                    user.setRoleIds(roleIds.toString());
                }
                if(roleNames.length()>0){
                	roleNames.deleteCharAt(roleNames.length()-1);
                    user.setRoleNames(roleNames.toString());
                }
            }
            return user;
        }
        return null;
    }

   
	 /**
     * 修改密码
     * @param dto
	 * @throws Exception 
     */
	public BussinessMsg updatePassword(PwdDto dto) throws Exception {
		logger.info("修改密码开始,当前用户Id:"+dto.getUserId());
        long start = System.currentTimeMillis();
        try {
    		int result = userDao.updatePassword(dto.getUserId(),MD5Utils.encrytor(dto.getPassword()),MD5Utils.encrytor(dto.getEditpwd()));
    		if(result==0){
    			return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_PASS_FAIL);
    		}
        } catch (Exception e) {
        	logger.error("修改密码方法内部错误",e);
            throw e;
        }finally {
        	logger.info("修改密码结束,用时" + (System.currentTimeMillis() - start) + "毫秒");
        }
        return BussinessMsgUtil.returnCodeMessage(BussinessCode.GLOBAL_SUCCESS);
	}
}
